package com.hnucm.cooklife.presenter.me;

import com.hnucm.cooklife.base.BasePresenter;
import com.hnucm.cooklife.bean.me.LoginData;
import com.hnucm.cooklife.contract.login.Contract;
import com.hnucm.cooklife.model.LoginModel;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class LoginPresenter extends BasePresenter<Contract.ILoginView> implements Contract.ILoginPresenter {

    Contract.ILoginModel mILoginModel;

    public LoginPresenter() {
        mILoginModel = new LoginModel();
    }

    @Override
    public void login(String username, String password) {
//        if(isViewAttached()){
//            getView().onLoading();
//        } else {
//            return;
//        }
        mILoginModel.login(username, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginData>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mCompositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull LoginData loginData) {
                        if(isViewAttached()){
                            getView().onLogin(loginData);
                            getView().onLoadSuccess();
                        }
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        e.printStackTrace();
                        if(isViewAttached()){
                            getView().onLoadingFailed();
                        }
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
